<template>
  <div id="userLoginPage">
    <h1>用户登录</h1>

    <el-form :model="form" ref="formRef" label-width="80px">
      <el-form-item label="账号" prop="userAccount">
        <el-input v-model="form.userAccount" clearable placeholder="账号应不少于 4 个字符" />
      </el-form-item>
      <el-form-item label="密码" prop="userPassword">
        <el-input v-model="form.userPassword" show-password autocomplete="off" placeholder="密码应不少于 6 个字符" />
      </el-form-item>    
    </el-form>
    
    <el-row id="userLoginButtons" :gutter="20" justify="space-between">
      <el-col :span="8" :offset="0">
        <el-button type="primary" size="large" @click="router.push('/user/register')" plain>注册账号</el-button>
      </el-col>
      <el-col :span="8" :offset="0">
        <el-button type="success" size="large" @click="fillHRInfo" :loading="loginButtonIsLoading">面试官登录</el-button>
      </el-col>
      <el-col :span="8" :offset="0">
        <el-button type="primary" size="large" @click="doLogin" :loading="loginButtonIsLoading">登录账号</el-button>
      </el-col>
    </el-row>
    
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from "vue";
import { userLoginUsingPost } from "@/api/userController";
import { useLoginUserStore } from "@/stores/userStore";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";
import { ResponseCodeEnum } from "@/enums";

const loginUserStore = useLoginUserStore();
const router = useRouter();

// 表单数据
const form = reactive<API.UserLoginRequest>({
  userAccount: "",
  userPassword: "",
});

// 登录按钮的加载效果
const loginButtonIsLoading = ref(false);

// 登录按钮点击事件
const doLogin = async () => {
  // 尝试登录
  loginButtonIsLoading.value = true;
  const result = await userLoginUsingPost(form);
  loginButtonIsLoading.value = false;

  if (result.data.code === ResponseCodeEnum.SUCCESS) {
    // 登录成功, 则刷新用户信息, 并重定向到首页
    loginUserStore.loginUser = result.data.data as API.LoginUserVO;

    ElMessage.success("登录成功");
    router.replace("/");
  } else {
    ElMessage.error("登录失败: " + result.data.message);
  }
};

/**
 * 填充 HR 信息
 */
const fillHRInfo = () => {
  form.userAccount = "interviewer";
  form.userPassword = "interviewer";
  ElMessage.success("已填入面试官信息: 用户名 interviewer, 密码 interviewer");
};
</script>

<style scoped>
#userLoginPage {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;

  width: 100%;
  height: 100%;
}

#userLoginPage .el-form {
  width: 100%;
}

#userLoginButtons {
  width: 100%;
}

.el-button {
  width: 100%;
}
</style>